package com.wu.util;

import lombok.Data;
import org.apache.commons.lang3.ObjectUtils;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @ClassName: ListOperateUtils
 * @Author: xiaox
 * @Description: 集合操作
 * @Date: 2022/7/15 17:58
 * @Version: 1.0
 */
@Data
public class ListOperateUtils {

	/****
	 * !!!!!!!! baseList 数据重复可能导致死循环，注意，去重
	 * @param <T>
	 * @param baseList
	 * @param size
	 * @return
	 */
    public static <T> List<T> randomGet(List<T> baseList, Integer size) {
        if (size <= 0 || ObjectUtils.isEmpty(baseList)) {
            return List.of();
        }
        int resultSize = Math.min(size, baseList.size());
        // 使用 ThreadLocalRandom 和 BitSet 生成随机索引下标
        BitSet used = new BitSet(baseList.size());
        List<T> result = new ArrayList<>(resultSize);
        ThreadLocalRandom random = ThreadLocalRandom.current();

        while (result.size() < resultSize) {
            int index = random.nextInt(baseList.size());
            if (!used.get(index)) {
                used.set(index);
                result.add(baseList.get(index));
            }
        }
        return result;
    }

}
